package com.slz3.business.frame.sync;

import com.slz3.business.frame.module.DomainEntity;
import com.slz3.business.frame.redis.RK;
import com.slz3.business.frame.util.VE;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@Slf4j
public class SyncPGToRedisSteward {

    public static List<UUID> uuidList(DomainEntity domainEntity) {
        List<UUID> uuidList = new ArrayList<>();
        UUID uuid = domainEntity.getUuid();
        if (uuid == null) {
            try {
                Field field = domainEntity.getClass().getDeclaredField("uuidList");
                field.setAccessible(true);
                Object fieldValue = field.get(domainEntity);
                uuidList = (ArrayList) Optional.ofNullable(fieldValue).orElse(new ArrayList<>());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (uuid != null && uuidList.size() == 0) {
            uuidList.add(uuid);
        }
        return uuidList;
    }

    public static String incrementIdMapUuidKey(DomainEntity domain) {
        try {
            Field field = domain.getClass().getDeclaredField("incrementId");
            //check
            if (VE.isNotEmptyArr(field, domain.getUuid())) {
                // 设置权限，保证对private的访问
                field.setAccessible(true);
                return String.format("%s:%s:%s", RK.ID_MAP_UUID, RK.BUSINESS, field.get(domain).toString());
            } else {
                return null;
            }
        } catch (NoSuchFieldException nsfe) {
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return null;
        }
    }

}
